package com.yaozheng.vocationaltraining.activity;

import java.io.File;
import java.io.IOException;

import net.sf.json.JSONObject;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.SeekBarProgressChange;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.yaozheng.vocationaltraining.R;
import com.yaozheng.vocationaltraining.db.CoursewareCacheDao;
import com.yaozheng.vocationaltraining.iview.ITokenBaseView;
import com.yaozheng.vocationaltraining.iview.IVideoCoursewareOperatingView;
import com.yaozheng.vocationaltraining.iview.IVideoCoursewareView;
import com.yaozheng.vocationaltraining.service.CoursewareDetailOperatingService;
import com.yaozheng.vocationaltraining.service.CoursewareDetailService;
import com.yaozheng.vocationaltraining.service.DownloadStatusListenerService;
import com.yaozheng.vocationaltraining.service.impl.CoursewareDetailOperatingServiceImpl;
import com.yaozheng.vocationaltraining.service.impl.CoursewareDetailServiceImpl;
import com.yaozheng.vocationaltraining.service.impl.VideoCoursewareDownloadServiceImpl;
import com.yaozheng.vocationaltraining.utils.ErrorUtils;
import com.yaozheng.vocationaltraining.utils.FileUtils;
import com.yaozheng.vocationaltraining.utils.JsonUtils;
import com.yaozheng.vocationaltraining.utils.StringUtils;
import com.yaozheng.vocationaltraining.utils.TypeUtils;
import com.yaozheng.vocationaltraining.view.VideoCoursewareDetailView;

/**
 * 视频课件详情
 *
 * @author Administrator
 */
@EActivity(R.layout.activity_video_courseware_detail)
public class VideoCoursewareDetailActivity extends BaseActivity implements
        IVideoCoursewareView, IVideoCoursewareOperatingView,
        SurfaceHolder.Callback, MediaPlayer.OnCompletionListener,
        MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
        OnBufferingUpdateListener {
    @Extra
    String title;
    @ViewById
    TextView coursewareTitleText, broadcastTimeTextView, videoSumTimeTextView;
    @ViewById
    SeekBar videoSeekBar;

    MediaPlayer player;
    @ViewById
    VideoCoursewareDetailView coursewareDetailView;

    File file;
    @ViewById
    ImageView benginBroadcastButton, fullScreenImage;
    @Bean(CoursewareDetailServiceImpl.class)
    CoursewareDetailService coursewareDetailService;
    @Bean(CoursewareDetailOperatingServiceImpl.class)
    CoursewareDetailOperatingService coursewareDetailOperatingService;
    @Bean(VideoCoursewareDownloadServiceImpl.class)
    DownloadStatusListenerService downloadStatusListenerService;
    JSONObject currCourserJsonObject, courserJsonObject;
    @ViewById
    View customVideoViewLayout, videoMuneLayout;
    @ViewById
    SurfaceView surface;
    SurfaceHolder surfaceHolder;
    private long videoTimeLong;

    int currentPosition;

    boolean isShowMune = true;

    /**
     * seekBar是否自动拖动
     */
    private boolean seekBarAutoFlag = false;

    boolean isFullScreen;
    /**
     * 课件下载按钮操作
     */
    int coursewareOperating;

    CoursewareCacheDao coursewareCacheDao;
    /**
     * true 读上一次数据
     */
    boolean isReadLastData;

    @Override
    protected void onCreate(Bundle arg0) {
        super.onCreate(arg0);
    }

    @AfterViews
    public void initView() {

        setHeadTitle(title);
        surfaceHolder = surface.getHolder();// SurfaceHolder是SurfaceView的控制接口
        surfaceHolder.addCallback(this); // 因为这个类实现了SurfaceHolder.Callback接口，所以回调参数直接this
        surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);// Surface类型
        seekBarAutoFlag = false;
        coursewareDetailService.init(this);
        coursewareDetailView.init(this);
        downloadStatusListenerService.init(this);
        coursewareDetailOperatingService.init(this);

        coursewareCacheDao = new CoursewareCacheDao(this);
        loadData();
        isFullScreen = false;
        isReadLastData = true;
        hideBenginBroadcastButton();

    }

    boolean isPause;

    @Override
    protected void onStart() {
        if (isPause) {
            if (player != null) {
                if (!player.isPlaying()) {
                    player.seekTo(currentPosition);
                    benginBroadcast();
                    isPause = false;
                }
            }
        }

        super.onStart();
    }

    public void onPause() {
        isPause = false;
        if (player != null) {
            if (player.isPlaying()) {
                currentPosition = player.getCurrentPosition();
                videoPause();
                isPause = true;
            }
        }
        super.onPause();
    }

    /**
     * 加载数据
     */
    public void loadData() {
        boolean isLoadNew = getIntentBoolean("isLoadNew", true);
        courserJsonObject = JsonUtils
                .getJsonObject(getIntentString("courserJsonStr"));
        this.currCourserJsonObject = coursewareCacheDao.get(TypeUtils
                .getJsonString(courserJsonObject, "id"));
        if (isLoadNew) {
            // 加载最新数据
            courserJsonObject.remove("format");
            if (currCourserJsonObject != null) {
                updateData();
            } else {

                coursewareTitleText.setText(TypeUtils.getJsonString(
                        courserJsonObject, "subject", ""));
                coursewareDetailView
                        .setVideoCoursewareDetailText(courserJsonObject);
            }
            coursewareDetailService.getCourse(TypeUtils.getJsonInteger(
                    courserJsonObject, "id"));
        } else {
            // 不从服务器上加载数据
            if (this.currCourserJsonObject != null) {
                try {
                    coursewareCacheDao.save(courserJsonObject);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            this.currCourserJsonObject = courserJsonObject;
            updateData();
        }
    }

    /**
     * 隐藏开始播放按钮
     */
    public void hideBenginBroadcastButton() {
        benginBroadcastButton.setVisibility(View.INVISIBLE);
    }

    /**
     * 显示开始播放按钮
     */
    public void showBenginBroadcastButton() {
        benginBroadcastButton.setVisibility(View.VISIBLE);
    }

    /**
     * 显示视频菜单
     */
    public void showVideoMenu() {
        isShowMune = true;
        videoMuneLayout.setVisibility(View.VISIBLE);
        showBenginBroadcastButton();
        if (isFullScreen) {
            full(false);
        }
    }

    /**
     * 隐藏视频菜单
     */
    public void hideVideoMenu() {
        isShowMune = false;
        videoMuneLayout.setVisibility(View.GONE);
        hideBenginBroadcastButton();
        if (isFullScreen) {
            full(true);
        }
    }

    /**
     * surface 点击
     */
    @Click(R.id.surface)
    public void surfaceClick() {
        if (isShowMune) {
            hideVideoMenu();
        } else {
            showVideoMenu();
        }
    }

    @Click(R.id.benginBroadcastButton)
    public void benginBroadcastClick() {
        if (player == null)
            return;
        if (player.isPlaying()) {
            videoPause();
        } else {
            benginBroadcast();
        }
    }

    /**
     * 开始播放
     */
    public void benginBroadcast() {
        try {
            if (player != null) {

                player.start();
                if (!seekBarAutoFlag) {
                    broadcastTiming();
                }
                getWindow().addFlags(
                        WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
                hideVideoMenu();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 暂停
     */
    public void videoPause() {
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        if (player.isPlaying()) {
            seekBarAutoFlag = false;
            player.pause();
        }
    }

    /**
     * 复制文件
     */
    @Background
    public void copyFile() {
        try {
            if (FileUtils.copyFile(getAssets().open("test_video.mp4"), file)) {
                copyFileSuccess();
            } else {
                copyFileError();
            }
        } catch (IOException e) {
            ErrorUtils.outErrorLog(e);
        }
    }

    @UiThread
    public void copyFileSuccess() {
        benginBroadcast();
        getProgressDialog().cancel();
    }

    @UiThread
    public void copyFileError() {
        alertMessage("复制出错 sd卡原因");
        getProgressDialog().cancel();
    }

    /**
     * 屏幕旋转完成时调用
     */
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onRestoreInstanceState(savedInstanceState);

    }

    public void onConfigurationChanged(Configuration newConfig) {
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            // 在横屏的情况下,跳转

            RelativeLayout.LayoutParams customVideoViewLayoutPara = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.FILL_PARENT,
                    RelativeLayout.LayoutParams.FILL_PARENT);
            customVideoViewLayout.setLayoutParams(customVideoViewLayoutPara);
            RelativeLayout.LayoutParams surfaceLayoutParams = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.FILL_PARENT,
                    RelativeLayout.LayoutParams.FILL_PARENT);
            surface.setLayoutParams(surfaceLayoutParams);

            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            isFullScreen = true;

        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            int videoCoursewareImageHeight = getResources()
                    .getDimensionPixelOffset(
                            R.dimen.video_courseware_image_height);
            // 在竖直情况下，跳转
            RelativeLayout.LayoutParams customVideoViewLayoutPara = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.FILL_PARENT,
                    videoCoursewareImageHeight);
            int defaultMargin = getResources().getDimensionPixelOffset(
                    R.dimen.default_margin);
            customVideoViewLayoutPara.setMargins(defaultMargin, 0,
                    defaultMargin, 0);
            customVideoViewLayoutPara.addRule(RelativeLayout.BELOW,
                    R.id.coursewareTitleText);

            customVideoViewLayout.setLayoutParams(customVideoViewLayoutPara);

            RelativeLayout.LayoutParams surfaceLayoutParams = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.FILL_PARENT,
                    videoCoursewareImageHeight);
            surface.setLayoutParams(surfaceLayoutParams);
            getWindow().clearFlags(
                    WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
            getWindow().clearFlags(
                    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            isFullScreen = false;
            full(isFullScreen);

        }
        super.onConfigurationChanged(newConfig);
    }

    /**
     * 设置是否隐藏状态栏
     *
     * @param enable
     */
    private void full(boolean enable) {
        if (enable) {
            // 隐藏状态栏
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            getWindow().setAttributes(lp);

        } else {
            // 显示状态栏
            WindowManager.LayoutParams attr = getWindow().getAttributes();
            attr.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(attr);
            // getWindow().clearFlags(
            // WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);

        }
    }

    /**
     * 全屏
     */
    @Click(R.id.fullScreenImage)
    public void fullScreenClick() {
        if (isFullScreen) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }

    @UiThread
    @Override
    public void responseSuccess(JSONObject jsonObject) {
        cancelLoadDataProgressDialog();
        JSONObject courserJsonObject = TypeUtils.getJsonObject(jsonObject,
                "data", "course");
        if (courserJsonObject != null) {
            if (this.currCourserJsonObject != null) {
                try {
                    coursewareCacheDao.save(courserJsonObject);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            updateData();
        }
    }

    /**
     * 更新数据
     */
    public void updateData() {
        if (this.currCourserJsonObject != null) {

            this.currCourserJsonObject = courserJsonObject;
            SharedPreferences sharedPreferences = getCurrUserSharedPreferences();
            int id = TypeUtils.getJsonInteger(currCourserJsonObject, "id");
            currentPosition = sharedPreferences.getInt("id_" + id, 0);
            coursewareTitleText.setText(TypeUtils.getJsonString(
                    currCourserJsonObject, "subject", ""));
            coursewareDetailView
                    .setVideoCoursewareDetailText(currCourserJsonObject);
            // TypeUtils.getJsonObject(currCourserJsonObject, "resources").put(
            // "video", "http://192.168.1.6:8080/Test/test_video.mp4");
            bindingPlayerResources();
        }
    }

    @UiThread
    @Override
    public void responseError(String error) {
        cancelLoadDataProgressDialog();
        if (this.currCourserJsonObject == null) {
            alertMessage(error);
        }
    }

    @Override
    public boolean isResponseResult() {
        return !isFinishing();
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        player = new MediaPlayer();
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        player.setDisplay(surfaceHolder);
        // 设置播放完成监听
        player.setOnCompletionListener(this);
        // 设置媒体加载完成以后回调函数。
        player.setOnPreparedListener(this);
        // 错误监听回调函数
        player.setOnErrorListener(this);
        // 设置缓存变化监听
        player.setOnBufferingUpdateListener(this);

        bindingPlayerResources();
    }

    /**
     * 绑定视频资源
     */
    public void bindingPlayerResources() {
        if (currCourserJsonObject == null)
            return;
        if (player == null)
            return;
        try {
            String localVideoFilePath = getLocalVideoFilePath();
            if (localVideoFilePath == null) {
                Uri uri = Uri.parse(TypeUtils.getJsonString(TypeUtils
                                .getJsonObject(currCourserJsonObject, "resources"),
                        "video"));
                player.setDataSource(this, uri);
                showDownloadCoursewareOperatingBut();
            } else {
                player.setDataSource(localVideoFilePath);
                hideDownloadCoursewareOperatingBut();
            }

            player.prepareAsync();
            // if (isPause) {
            // player.seekTo(currentPosition);
            // benginBroadcast();
            // isPause = false;
            // }

        } catch (Exception e) {
            // e.printStackTrace();
            ErrorUtils.outErrorLog(e);
        }

    }

    /**
     * 得到本地缓存视频目录
     *
     * @return null 说明本地没这视频
     */
    public String getLocalVideoFilePath() {
        if (courserJsonObject != null) {
            File file = new File(
                    getLocalVideoCacheDir(),
                    TypeUtils.getJsonString(courserJsonObject, "id")
                            + VideoCoursewareDownloadServiceImpl.VIDEO_COURSEWARE_EXTENSION);
            if (file.exists()) {
                return file.getAbsolutePath();
            } else {
                return null;
            }
        }
        return null;
    }

    /**
     * 得到本地视频文件目录
     *
     * @return
     */
    public String getLocalVideoFilePath(String id) {
        return "";
    }

    /**
     * seekBar拖动监听类
     *
     * @author shenxiaolei
     */
    @SeekBarProgressChange(R.id.videoSeekBar)
    public void onProgressChanged(SeekBar seekBar, int progress,
                                  boolean fromUser) {
        if (progress >= 0) {
            // 如果是用户手动拖动控件，则设置视频跳转。
            if (fromUser) {
                player.seekTo(progress);
            }
            // 设置当前播放时间
            broadcastTimeTextView.setText(StringUtils.getShowTime(progress));
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {
        // TODO Auto-generated method stub

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        releasePlayer();
    }

    /**
     * 视频缓存大小监听,当视频播放以后 在started状态会调用
     */
    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
    }

    /**
     * 错误监听
     *
     * @param mp
     * @param what
     * @param extra
     * @return
     */
    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        if (what == MediaPlayer.MEDIA_ERROR_SERVER_DIED) {
            alertMessage("视频文件出现错误。");
        } else if (what == MediaPlayer.MEDIA_ERROR_UNKNOWN) {
            alertMessage("视频文件不存在。");
        } else if (what == MediaPlayer.MEDIA_ERROR_IO) {
            alertMessage("文件或网络相关的操作错误。");
        } else if (what == MediaPlayer.MEDIA_ERROR_MALFORMED) {
            alertMessage("比特流不符合相关的编码标准或文件规范。");
        } else if (what == MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK) {
            alertMessage("视频文件出现问题。");
        } else if (what == MediaPlayer.MEDIA_ERROR_TIMED_OUT) {
            alertMessage("操作超时。");
        } else if (what == MediaPlayer.MEDIA_ERROR_UNSUPPORTED) {
            alertMessage("比特流符合相关的编码标准或文件规范，但媒体框架不支持该功能。");
        } else if (what == 261) {
            alertMessage("播放错误。播放文件404");
        }
        return true;
    }

    /**
     * 视频加载完毕监听
     *
     * @param mp
     */
    @Override
    public void onPrepared(MediaPlayer mp) {
        if (isPause) {
            player.seekTo(currentPosition);
            benginBroadcast();
            isPause = false;
        } else {
            videoTimeLong = player.getDuration();
            videoSeekBar.setMax((int) videoTimeLong);
            videoSumTimeTextView
                    .setText(StringUtils.getShowTime(videoTimeLong));
            broadcastTimeTextView.setText("00:00");
            // showBenginBroadcastButton();

            if (isReadLastData) {
                if (currCourserJsonObject != null) {

                    if (currentPosition >= (player.getDuration() - 120)) {
                        currentPosition = 0;
                    } else {
                        videoSeekBar.setProgress(currentPosition);
                    }
                    player.seekTo(currentPosition);

                    isReadLastData = false;
                }
            }
            showVideoMenu();
        }

    }

    /**
     * 播放完毕监听
     *
     * @param mp
     */
    @Override
    public void onCompletion(MediaPlayer mp) {
        alertMessage("播放结束");
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        showVideoMenu();
        if (isFullScreen) {
            fullScreenClick();
        }
    }

    /**
     * 播放计时
     */
    @Background
    public void broadcastTiming() {
        seekBarAutoFlag = true;
        // 增加对异常的捕获，防止在判断mediaPlayer.isPlaying的时候，报IllegalStateException异常
        try {
            while (seekBarAutoFlag) {
                /*
                 * mediaPlayer不为空且处于正在播放状态时，使进度条滚动。
				 * 通过指定类名的方式判断mediaPlayer防止状态发生不一致
				 */
                if (isResponseResult()) {
                    if (null != player && player.isPlaying()) {
                        videoSeekBar.setProgress(player.getCurrentPosition());
                    }
                } else {
                    return;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getLocalVideoCacheDir() {
        return getResourcesCachePath() + getString(R.string.cacheRootDriStr)
                + getString(R.string.videoCacheDir);
    }

    @UiThread
    @Override
    public void downloadVideoError(String error) {
        coursewareOperating = 0;
        alertMessage(error);
    }

    @UiThread
    @Override
    public void downloadStatusChange(double completionRate) {
        int currCompletionRate = (int) (Math.ceil(completionRate * 100));
        coursewareDetailView.getCoursewareOperatingBut().setText(
                currCompletionRate + "%");
    }

    @UiThread
    @Override
    public void downloadSuccess() {
        alertMessage("课件下载成功");
        if (currCourserJsonObject != null) {
            int id = TypeUtils.getJsonInteger(currCourserJsonObject, "id");
            coursewareDetailOperatingService.submitServerDownloadSuccess(id);
            currCourserJsonObject.put("download_cnt", TypeUtils.getJsonInteger(
                    currCourserJsonObject, "download_cnt") + 1);
            coursewareDetailView
                    .setVideoCoursewareDetailText(currCourserJsonObject);

            try {
                coursewareCacheDao.save(currCourserJsonObject);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        hideDownloadCoursewareOperatingBut();
        if (player != null) {
            if (!player.isPlaying()) {
                bindingPlayerResources();
            }
        }
    }

    /**
     * 隐藏下载课件按钮
     */
    public void hideDownloadCoursewareOperatingBut() {
        coursewareDetailView.getCoursewareOperatingBut().setVisibility(
                View.GONE);
    }

    /**
     * 显示下载课件按钮
     */
    public void showDownloadCoursewareOperatingBut() {
        coursewareDetailView.getCoursewareOperatingBut().setVisibility(
                View.VISIBLE);
    }

    @Override
    public void coursewareOperatingButClick() {
        if (currCourserJsonObject == null)
            return;
        if (coursewareOperating == 0) {
            downloadStatusListenerService.download(currCourserJsonObject);
            coursewareDetailView.getCoursewareOperatingBut().setText("下载中");
            coursewareOperating = 1;
        }
    }

    @Override
    public void saveProgressSuccess(JSONObject jsonObject) {
        // TODO Auto-generated method stub

    }

    @Override
    public void saveProgressError(String error) {
        // TODO Auto-generated method stub

    }

    @Override
    public void submitServerDownloadSuccess(JSONObject jsonObject) {
        // TODO Auto-generated method stub

    }

    @Override
    public void submitServerDownloadError(String error) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onBackPressed() {
        if (isFullScreen) {
            fullScreenClick();
            return;
        }
        releasePlayer();
        super.onBackPressed();
    }

    /**
     * 释放资源
     */
    public void releasePlayer() {
        // 由于MediaPlay非常占用资源，所以建议屏幕当前activity销毁时，则直接销毁
        try {
            if (null != player) {
                // 提前标志为false,防止在视频停止时，线程仍在运行。
                seekBarAutoFlag = false;

                // 如果正在播放，则停止。
                if (player.isPlaying()) {
                    player.stop();
                }
                if (currCourserJsonObject != null) {
                    int currentPosition = player.getCurrentPosition();
                    if (currentPosition == 0) {
                        currentPosition = this.currentPosition;
                    }
                    SharedPreferences sharedPreferences = getCurrUserSharedPreferences();
                    Editor editor = sharedPreferences.edit();
                    int id = TypeUtils.getJsonInteger(currCourserJsonObject,
                            "id");
                    coursewareDetailOperatingService.saveProgress(id,
                            currentPosition);
                    editor.putInt(
                            "id_"
                                    + TypeUtils.getJsonInteger(
                                    currCourserJsonObject, "id"),
                            currentPosition);
                    editor.commit();
                }
                // 释放mediaPlayer
                player.release();
                player = null;
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        releasePlayer();

        super.onDestroy();
    }
}
